/* Author: 
	Nicolaj Roos
*/
var current = 0;
var numberOfImages = 0;
var bodyWidth;
var bodyHeight;
var imgWidthOrg;
var imgHeightOrg;
var imgWidth;
var imgHeight;
var ratio;
var counter = 0;
var currentImage, oldImage;
var images;
var footerTxt;

var tempImage, tempBody;

var $xml;



function formFadeIn(){
	$('#lightbox').fadeTo(500, 0.5);
	$('#form').fadeTo(500, 1);
}

function formFadeOut () {
	$('#form, #lightbox').fadeOut(500);
}

$(window).load(function(){
		
	$.get('img/gallery.xml', function(d){
		$xml = $(d);
		continueLoad();
		//console.log($(d).find('image[sort=1]').text());	
		}
	);
		
		
});



function continueLoad(){
	$('#contactForm').submit( submitForm );
	$('#contactForm #cancel').click( function(e){
		e.preventDefault();
		formFadeOut();
		
	} );

	currentImage = new Image();
	oldImage = new Image();
	
	numberOfImages = $xml.find('image').length-1;	
	currentImage.src = getImageUrl(current);
    
	currentImage.onload = function() {

		imgWidthOrg = currentImage.width;
		imgHeightOrg = currentImage.height;

		$('#footerElement').click(function(e){
			e.preventDefault();
			formFadeIn();
		});

		if(imgWidthOrg > $('#main').width() || imgHeightOrg > $('#main').height()){
			
			// Her: Javascript metode til at resize!
						
			$('#main').append(currentImage);
			scaleImage($('#main img'));
			
		
		} else {
			
			// Her: Javascript metode til at resize!
			$('#main').append(currentImage);
		};
		

	//currentImage.css('display','inline');
	//scaleImage(currentImage);
		
	}
	currentImage.src = getImageUrl(current);
};
	
	
function scaleSize(maxW, maxH, currW, currH){

	var ratioImage = currH / currW;
	var ratioBox = maxH / maxW;
	
	//footer(currW+" > "+maxW+", eller "+currH+" > "+maxH);
	if(currW > maxW || currH > maxH)
	{
		//footer(ratioImage+" > "+ratioBox);
		if(ratioImage > ratioBox){
			// Landscape
			//footer("Landscape");
			currH = maxH;
			currW = currH / ratioImage;	
		} else {
			// Portrait
			//footer("Portrait");
			currW = maxW;
			currH = currW * ratioImage;
		}
	}
	
	return [currW, currH];
}	
	
$(window).resize(function () { 
	scaleImage($('#main img'));
	});

function scaleImage(pic) {

	tempBody = $('#main');
	//footer(tempBody.width()+" * "+ tempBody.height());
	//footer(imgWidthOrg+" * "+ imgHeightOrg);
	var newSize = scaleSize(tempBody.width(), tempBody.height(), imgWidthOrg, imgHeightOrg);
	//footer(newSize[0]+" ** "+newSize[1]);
	
	var margin = (tempBody.height()-newSize[1])/2;
	if (margin >=0) pic.css('margin-top', margin+"px");
	pic.width(newSize[0]).height(newSize[1]);
}

function getImageUrl(sort){
	return "img/gallery/" + $xml.find("image[sort="+sort+"] > url").text();
}

$(document).bind('keydown', handler);


function handler(e){
	if (e.keyCode == 37) { 
       prev();
       return false;
    }
    if (e.keyCode == 39) { 
       next();
       return false;
    }
	
}

function prev(){
	//var previous = current;
	oldImage = currentImage;

	if(current == 0){
		current = numberOfImages;
	} else {
		current--;
	}

	showCurrent(oldImage);
}

function next(){

	//oldImage = currentImage;

	if(current == numberOfImages){
		current = 0;
	} else {
		current++;
	}

	showCurrent();
}

function showCurrent(){

	//currentImage = new Image();
	//currentImage.src = images[current];
	
	//currentImage.onload = function() {

	//imgWidthOrg = currentImage.width;
	//imgHeightOrg = currentImage.height;
		
	// Fade gammelt indhold ud
	$('#main').fadeOut("slow", 
		function() {
			$('#main img').remove();
			currentImage = document.createElement('img');
						
			currentImage.onload = function(){
				//alert("XXX");
				imgWidthOrg = currentImage.width;
				imgHeightOrg = currentImage.height;
				//alert(imgWidthOrg+" * "+imgHeightOrg);
				
				// Når fadeout er slut:
				// Fade nyt indhold ind	
				
				if(imgWidthOrg > $('#main').width() || imgHeightOrg > $('#main').height()){
					
					// Her: Javascript metode til at resize!
					//$("#main img").attr("src", images[current]);
									
					//$('#main').append(html);
					
					
					$('#main').append(currentImage);
					scaleImage($('#main img'));
					
					
					
				} else {
					
					// Her: Javascript metode til at resize!
					
					tempBody = $('#main');
					var margin = (tempBody.height()-currentImage.height)/2;
					if (margin >=0) $(currentImage).css('margin-top', margin+"px");
					
					
					$('#main').append(currentImage);
					//$("#main img").attr("src", images[current]);
					
				};
		
				$('#main').fadeIn("slow");
			}
			currentImage.src = getImageUrl(current);

			// Sæt tekst ind
			//var alt = $('img:eq('+newImage+')').attr('alt');
			//$('h2').html(alt);
		}
	);
	//}					
}

function footer(s){
	$('footer').html(s);
}

var messageDelay = 2000;  // How long to display status messages (in milliseconds)

function submitForm() {
  var contactForm = $(this);

  // Are all the fields filled in?

  if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {
    // No; display a warning message and return to the form
    $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();

    contactForm.fadeOut().delay(messageDelay).fadeIn();

  } else {

    // Yes; submit the form to the PHP script via Ajax

    $('#sendingMessage').fadeIn();
    contactForm.fadeOut();

    $.ajax( {
      url: contactForm.attr( 'action' ) + "?ajax=true",
      type: contactForm.attr( 'method' ),
      data: contactForm.serialize(),
      success: submitFinished
    } );
  }

  // Prevent the default form submission occurring
  return false;
}


// Handle the Ajax response

function submitFinished( response ) {
  response = $.trim( response );
  $('#sendingMessage').fadeOut();

  if ( response == "success" ) {

    // Form submitted successfully:
    // 1. Display the success message
    // 2. Clear the form fields
    // 3. Fade the content back in

    $('#successMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#senderName').val( "" );
    $('#senderEmail').val( "" );
    $('#message').val( "" );

    $('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );

  } else {

    // Form submission failed: Display the failure message,
    // then redisplay the form
    $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#contactForm').delay(messageDelay+500).fadeIn();
  }
}
	
	
	
